package com.example.demo.mapper;

import com.example.demo.dto.CartItemDetailsDTO;
import com.example.demo.entity.ShoppingCart;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 购物车管理 Mapper 接口
 * </p>
 */
@Mapper
public interface ShoppingCartMapper extends BaseMapper<ShoppingCart> {
    @Select("SELECT * FROM shopping_cart WHERE s_user_id = #{userId}")
    List<ShoppingCart> selectByUserId(@Param("userId") Integer userId);

    @Select("SELECT * FROM shopping_cart WHERE s_user_id = #{userId} AND s_goods_id = #{goodsId}")
    ShoppingCart selectByUserAndGoods(@Param("userId") Integer userId,
                                      @Param("goodsId") Integer goodsId);

    @Delete("DELETE FROM shopping_cart WHERE s_user_id = #{userId}")
    int deleteByUserId(@Param("userId") Integer userId);

    // 获取用户购物车商品总数
    @Select("SELECT  COUNT(*) FROM shopping_cart WHERE s_user_id = #{userId}")
    Integer getTotalCartItems(@Param("userId") Integer userId);

    // 获取用户购物车总金额
    @Select("SELECT SUM(g.g_price * s.s_quantity) " +
            "FROM shopping_cart s " +
            "JOIN goods g ON s.s_goods_id = g.g_id " +
            "WHERE s.s_user_id = #{userId}")
    BigDecimal getCartTotalAmount(@Param("userId") Integer userId);

    // 批量删除购物车商品
    @Delete({
            "<script>",
            "DELETE FROM shopping_cart WHERE s_id IN",
            "<foreach item='id' collection='ids' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    int batchDeleteCartItems(@Param("ids") List<Integer> cartItemIds);


    @Select("SELECT COUNT(*) FROM shopping_cart WHERE s_goods_id = #{goodsId}")
    int countByGoodsId(@Param("goodsId") Integer goodsId);
    @Select("SELECT s_quantity FROM shopping_cart " +
            "WHERE s_goods_id = #{goodsId} AND s_user_id = #{userId}")
    int countByGoodsIdAndUserId(@Param("goodsId") Integer goodsId,
                                @Param("userId") Integer userId);

    @Update("UPDATE shopping_cart SET s_quantity = #{quantity} WHERE s_user_id = #{sUserId} AND s_goods_id = #{sGoodsId}")
    boolean updateQuantityByUserIdAndGoodsId(
            @Param("sUserId") Integer sUserId,
            @Param("sGoodsId") Integer sGoodsId,
            @Param("quantity") Integer quantity
    );

    // 在ShoppingCartMapper中添加
    @Select("SELECT sc.s_id AS cartId, sc.s_quantity AS quantity, " +
            "g.g_id AS goodsId, g.g_name AS name, g.g_price AS price, " +
            "g.g_stock_quantity AS stock, g.g_category AS category " +
            "FROM shopping_cart sc " +
            "JOIN goods g ON sc.s_goods_id = g.g_id " +
            "WHERE sc.s_user_id = #{userId}")
    List<CartItemDetailsDTO> selectCartDetailsByUserId(@Param("userId") Integer userId);
}
